﻿using Pay.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Pay.Http.Utilitys
{
    public class HttpClientHelper
    {
        private static HttpClient GetHttpClient(IDictionary<string, string> headers = null)
        {
            var client = new HttpClient();
            if (headers != null)
            {
                if (headers.Any())
                {
                    foreach (var h in headers)
                    {
                        client.DefaultRequestHeaders.Add(h.Key, h.Value);
                    }
                }
            }
            return client;
        }

        public static async Task<HttpResponseMessage> GetAsync(string requestUri, IDictionary<string, string> headers = null)
        {
            var client = GetHttpClient(headers);
            return await client.GetAsync(requestUri);
        }

        public static async Task<string> GetStrngAsync(string requestUri, IDictionary<string, string> headers = null)
        {
            var response = await GetAsync(requestUri, headers);
            return await response.Content.ReadAsStringAsync();
        }

        public static async Task<T> GetJsonAsync<T>(string requestUri, IDictionary<string, string> headers = null)
        {
            var htmlString = await GetStrngAsync(requestUri, headers);
            if (string.IsNullOrWhiteSpace(htmlString))
                return default(T);
            return JsonHelper.DeserializeObject<T>(htmlString);
        }

        public static async Task<T> GetAnonymousType<T>(string requestUri, T anonymousTypeObject, IDictionary<string, string> headers = null)
        {
            var htmlString = await GetStrngAsync(requestUri, headers);
            if (string.IsNullOrWhiteSpace(htmlString))
                return default(T);
            return JsonHelper.DeserializeAnonymousType(htmlString, anonymousTypeObject);
        }

        public static async Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent httpContent = null, IDictionary<string, string> headers = null)
        {
            var client = GetHttpClient(headers);
            return await client.PostAsync(requestUri, httpContent);
        }

        public static async Task<string> PostStrngAsync(string requestUri, HttpContent httpContent = null, IDictionary<string, string> headers = null)
        {
            var response = await PostAsync(requestUri, httpContent, headers);
            return await response.Content.ReadAsStringAsync();
        }

        public static async Task<T> PostJsonAsync<T>(string requestUri, HttpContent httpContent = null, IDictionary<string, string> headers = null)
        {
            var htmlString = await PostStrngAsync(requestUri, httpContent, headers);
            return JsonHelper.DeserializeObject<T>(htmlString);
        }
    }
}
